package ch14_advanced_gui;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JMouseActionsFrame extends JFrame implements MouseListener
{
   private final int MAX = 20;
   private final int STARTX = 10;
   private final int STARTY = 20;
   private int x, y;
   private String message[] = new String[MAX];
   private int msgCount = 0;

   public JMouseActionsFrame()
   {
       setTitle("Mouse Actions");
       setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       addMouseListener(this);
   }

   public void mouseClicked(MouseEvent e)
   {
      int whichButton = e.getButton();
      String msg;
      if(msgCount == MAX)
         clearScreen();
      message[msgCount] = "You pressed the mouse.";
      if(whichButton == MouseEvent.BUTTON1)
         msg = "button 1.";
      else if(whichButton == MouseEvent.BUTTON2)
         msg = "button 2.";
      else msg = "button 3.";
      message[msgCount] = message[msgCount] +
         " You used " + msg;
      message[msgCount] = message[msgCount]  +
         " You are at position " +
      e.getX() + ", " + e.getY() + ".";
     if(e.getClickCount() == 2)
        message[msgCount] = message[msgCount] +
           " You double-clicked";
     else
        message[msgCount] = message[msgCount] +
           " You single-clicked";
     ++msgCount;
     repaint();
   }
   public void mouseEntered(MouseEvent e)
   {
      if(msgCount == MAX)
         clearScreen();
      message[msgCount] = "You entered the frame";
      ++msgCount;
      repaint();
   }
   public void mouseExited(MouseEvent e)
   {
      if(msgCount == MAX)
         clearScreen();
      message[msgCount] = "You exited the frame";
      ++msgCount;
      repaint();
   }

  public void mousePressed(MouseEvent e)
  {
  }

  public void mouseReleased(MouseEvent e)
  {
  }

  public void paint(Graphics g)
  {
     final int SIZE = 20;
     super.paint(g);
     x = STARTX;
     y = STARTY;
     for(int a = 0; a < msgCount; ++a)
        g.drawString(message[a], x, y += SIZE);
  }

  public void clearScreen()
  {
    msgCount = 0;
    for(int a = 0; a < MAX; ++a)
        message[a] = " ";
    repaint();
  }
  public static void main(String[] args)
  {
    JMouseActionsFrame mFrame = new JMouseActionsFrame();
    final int WIDTH = 750;
    final int HEIGHT = 300;
    mFrame.setSize(WIDTH, HEIGHT);
    mFrame.setVisible(true);
  }
}
